package com.fileCenter.actions;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fileCenter.pojo.Model;
import com.fileCenter.service.ModelService;
import com.fileCenter.util.FcStringUtil;

public class ModelAction extends BaseAction {
	private ModelService modelService;
	
	public ActionForward viewInput(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		return mapping.findForward("success");
	}
	
	public ActionForward viewList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		System.out.println("===viewList===");
		List<Model> models = modelService.listByAttr(generateAttrNameAndValueMap(request));
		request.setAttribute("models", models);
		request.setAttribute("loginUser",  getLoginModel());
		return mapping.findForward("success");
	}
	
	private Map<String, Object> generateAttrNameAndValueMap (HttpServletRequest request) {
		Map<String, Object> attrNameAndValueMap = Collections.emptyMap();
		String name = request.getParameter("name");
		String realName = request.getParameter("realName");
		String sex = request.getParameter("sex");
		String modelId = request.getParameter("modelId");
		String level = request.getParameter("level");
		
		if(StringUtils.isNotBlank(name) || StringUtils.isNotBlank(realName) || StringUtils.isNotBlank(sex) 
				|| StringUtils.isNotBlank(modelId) || StringUtils.isNotBlank(level)){
			attrNameAndValueMap = new HashMap<String, Object>();
		}
		
		if (StringUtils.isNotBlank(name)) {
			attrNameAndValueMap.put("name", name);
		}
		if (StringUtils.isNotBlank(realName)) {
			attrNameAndValueMap.put("realName", realName);
		}
		if (StringUtils.isNotBlank(sex)) {
			attrNameAndValueMap.put("sex", FcStringUtil.getInt(sex));
		}
		if (StringUtils.isNotBlank(modelId)) {
			attrNameAndValueMap.put("modelId", FcStringUtil.getLong(modelId));
		}
		if (StringUtils.isNotBlank(level)) {
			attrNameAndValueMap.put("level", FcStringUtil.getInt(level));
		}
		
		return attrNameAndValueMap;
	}
	
	public void setModelService(ModelService modelService) {
		this.modelService = modelService;
	}
}
